package com.peitamerchants.ui.chat;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.peitamerchants.R;
import com.peitamerchants.api.CommonApi;
import com.peitamerchants.application.MainApplication;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;
import okhttp3.Response;

/**
 * Created by zy on 2017/7/3.
 */

public class ConversationListActivity extends AppCompatActivity{

    private final String TAG = ConversationListActivity.class.getSimpleName();
    private TextView tv_title;
    private Toolbar toolbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conversationlist);
        initRongImUri();
        initView();
        initData();
    }

    private void initView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tv_title = (TextView) findViewById(R.id.toobal_title);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        tv_title.setText("消息列表");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initData() {
            RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
                @Override
                public UserInfo getUserInfo(String userId) {
                    return getUserInfoFromServer(userId);
                }
            }, true);
            RongIM.setGroupInfoProvider(new RongIM.GroupInfoProvider() {
                @Override
                public Group getGroupInfo(String groupId) {
                    // TODO Auto-generated method stub
                    return  getGroupInfoFromServer(groupId);
                }
            }, true);
    }
    // 获群组信息
    private Group getGroupInfoFromServer(String groupId) {
        try {
            Response response = OkHttpUtils
                    .get()
                    .url(CommonApi.GROUP_DETAIL+ MainApplication.getTokenUrl() + "&group_id="+groupId)
                    .tag(this)
                    .build()
                    .execute();
            if(response != null){
                String result = response.body().string();
                Log.e(TAG, "群详情:"+result);
                try {
                    JSONObject object = new JSONObject(result);
                    int code =  object.getInt("code");
                    if(10000 == code){
                        object = object.getJSONObject("data");
                        String group_name = null;
                        if(!object.isNull("name")){
                            group_name = object.getString("name");
                        }
                        String group_img = null;
                        if(!object.isNull("group_img")){
                            group_img = object.getString("group_img");
                        }
                        return new Group(groupId, group_name, Uri.parse(CommonApi.USER_ICON+group_img));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }



            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    // 获取个人信息
    private UserInfo getUserInfoFromServer(String userId) {
        try {
            Response response = OkHttpUtils
                    .get()
                    .url(CommonApi.USER_DETAIL+MainApplication.getTokenUrl()+"&id=" + userId)
                    .tag(this)
                    .build()
                    .execute();
            if(response != null){
                String result = response.body().string();
                try {
                    JSONObject object = new JSONObject(result);
                    int code =  object.getInt("code");
                    if(10000 == code){
                        object = object.getJSONObject("data");
                        String username = null;
                        if(!object.isNull("username")){
                             username = object.getString("username");
                        }
                        String userIcon = null;
                        if(!object.isNull("user_head_img")){
                            userIcon = object.getString("user_head_img");
                        }
                        return new UserInfo(userId, username, Uri.parse(CommonApi.USER_ICON+userIcon));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void initRongImUri() {
        ConversationListFragment fragment = new ConversationListFragment();
        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("conversationlist")
                .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话非聚合显示
                .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "false")
                .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")
                .build();
        fragment.setUri(uri);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.activity_conversationlist_fragment, fragment);
        transaction.commitAllowingStateLoss();
    }
}
